package cn.janyd.jmall.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDateTime;

/**
 * @author janyd
 * @since 2020/8/5 20:08
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisCommonAutoConfiguration {

    /**
     * 自动注入createTime
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MetaObjectHandler() {
            private final static String CREATE_TIME_FIELD = "createTime";
            private final static String UPDATE_TIME_FIELD = "updateTime";

            /**
             * 插入元对象字段填充（用于插入时对公共字段的填充）
             *
             * @param metaObject 元对象
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                Object createTime = this.getFieldValByName(CREATE_TIME_FIELD, metaObject);
                if (null == createTime) {
                    this.setFieldValByName(CREATE_TIME_FIELD, LocalDateTime.now(), metaObject);
                }

                Object updateTime = this.getFieldValByName(UPDATE_TIME_FIELD, metaObject);
                if (null == updateTime) {
                    this.setFieldValByName(UPDATE_TIME_FIELD, LocalDateTime.now(), metaObject);
                }
            }

            /**
             * 更新元对象字段填充（用于更新时对公共字段的填充）
             *
             * @param metaObject 元对象
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName(UPDATE_TIME_FIELD, LocalDateTime.now(), metaObject);
            }
        };
    }

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean
    public ISqlInjector sqlInjector() {
        // MyBatis Plus 逻辑删除
        return new DefaultSqlInjector();
    }
}
